<template>
  <div class="page-container">
    <!-- 顶部按钮 -->
    <div class="btn-container">
      <el-button v-auth-btn="'parking:area:add_edit'" type="primary" size="medium" @click="onOpenDialog({})">添加区域</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="areaList" class="area-table" :header-cell-style="{ background: '#f7f8f9' }">
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column label="区域名称" prop="areaName" />
      <el-table-column label="车位数（个）" prop="spaceNumber" />
      <el-table-column label="面积（m²）" prop="areaProportion" />
      <el-table-column label="计费规则" prop="ruleName" />
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button v-auth-btn="'parking:area:add_edit'" type="text" size="medium" @click="onOpenDialog(row)">编辑</el-button>
          <el-button v-auth-btn="'parking:area:remove'" type="text" size="medium" @click="onDeleteArea(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination layout="->, total, prev, pager, next" :total="total" @current-change="onChangePage" />

    <!-- 区域编辑器弹窗 -->
    <AreaEditor ref="areaEditor" @refresh-area-list="getAreaList" />
  </div>
</template>

<script>
import { getAreaListAPI, deleteAreaAPI } from '@/api/car/cararea'

import AreaEditor from './components/AreaEditor'

export default {
  name: 'CarArea',
  components: {
    AreaEditor
  },
  data() {
    return {
      areaList: [],
      total: 0,
      searchParams: {
        page: 1,
        pageSize: 10
      }
    }
  },
  created() {
    // 获取区域列表
    this.getAreaList()
  },
  methods: {
    // 获取区域列表
    async getAreaList() {
      const res = await getAreaListAPI(this.searchParams)
      this.areaList = res.rows
      this.total = res.total
    },
    // 打开区域编辑器
    onOpenDialog(row) {
      // 打开区域编辑器，当点击添加区域时，参数id为undefined
      this.$refs.areaEditor.open(row)
    },
    // 删除区域
    async onDeleteArea(id) {
      await deleteAreaAPI(id)
      // 如果删除数据时当前页最后一条数据，且页码大于1，则页码减1
      if (this.areaList.length === 1 && this.page > 1) {
        this.page--
      }
      // 重新获取区域列表
      this.getAreaList()
      this.$message.success('删除成功')
    },
    // 切换分页器当前页
    onChangePage(val) {
      this.searchParams.page = val
      this.getAreaList()
    },
    // 切换到列表首页
    onChangeFirstPage() {
      this.searchParams.page = 1
      this.getAreaList()
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  .area-table {
    margin: 20px 0;
  }
}
</style>
